<?php

namespace app\admin\controller\communityinfo;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 社区信息发布
 *
 * @icon fa fa-newspaper-o
 */
class Communityinfo extends Backend
{
    /**
     * Slider模型对象
     * @var \app\admin\model\Slider
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Slider');
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法
     * 因此在当前控制器中可不用编写增删改查的代码
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $user= $this->auth->getUserInfo();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where("status","=",1)
            ->where("ocation_id","=",$user['ocation_id'])->order($sort, $order)
            ->paginate($limit);

        // 获取分页数据项并转换为数组
        $items = $list->items();
        $resultItems = [];
        
        foreach  ($items as  $key=>$row) {
            // 将模型对象转换为数组
            $rowData = $row->toArray();
            $rowData['ocation_name'] = model("Ocation")->where("id",$row['ocation_id'])->value('name');
            $images = json_decode($row['image'],true);
            $rowData['imageNew'] = [];
            if (is_array($images)) {
                foreach ($images as $key2 => $value2) {
                    $rowData['imageNew'][] = $value2;
                }
            }
            $rowData["image"] = $rowData['imageNew'];
            unset($rowData['imageNew']);
            $resultItems[] = $rowData;
        }

        $result = ['total' => $list->total(), 'rows' => $resultItems];
        return json($result);
    }

    /**
     * 添加
     */
    public function add()
    {
        $user = $this->auth->getUserInfo();
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['ocation_id'] = $user['ocation_id'];
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('添加成功', null, ['refresh' => true]);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $user = $this->auth->getUserInfo();
        $slider = model("Slider")->where("id",$ids)->find();
        if(!isset($slider['ocation_id'])||$slider['ocation_id'] != $user['ocation_id']){
            $slider=model("Slider")->create([
                'ocation_id' => $user['ocation_id'],
                'title' => "", //标题
                'image' => "", //图片
                'image_width' => 750, //图片宽度
                'image_height' => 422, //图片高度
                'status' => 1,
                'weigh' => 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ]);
        }
        $row = $this->model->where("ocation_id",$slider['ocation_id'])->find();

        if (!$row) {
            //如果不存在，则创建
            $ocation = model("Ocation")->where("id",$user['ocation_id'])->find();
            $row = $this->model->create([
                'ocation_id' => $user['ocation_id'],
                'title' => $ocation['name'], //标题
                'image' => '', //图片
                'image_width' => 800, //图片宽度
                'image_height' => 600, //图片高度
                'status' => 1,
                'weigh' => 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            $row = $this->model->where("ocation_id",$row['ocation_id'])->find();
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // 将slider的image数据传递给row，以便在编辑页面显示
            if ($slider && !empty($slider['image'])) {
                $row['image'] = $slider['image'];
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were updated'));
        }
        $this->success('编辑成功', null, ['refresh' => true]);
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('删除成功', null, ['refresh' => true]);
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 修改状态
     */
    public function changeStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        
        if (empty($id) || !in_array($status, ['0', '1'])) {
            $this->error(__('参数错误'));
        }
        
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('记录不存在'));
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        
        $row->status = $status;
        $result = $row->save();
        
        if ($result) {
            $this->success(__('操作成功'));
        } else {
            $this->error(__('操作失败'));
        }
    }


}